import pandas as pd
import numpy as np
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
from alpha_vantage.fundamentaldata import FundamentalData
import plotly.graph_objects as go
import plotly.express as px
import requests
import json
import requests
from flask import Flask
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
# import pandas as pd
# import numpy as np
# from alpha_vantage.timeseries import TimeSeries
# from alpha_vantage.techindicators import TechIndicators
# from alpha_vantage.fundamentaldata import FundamentalData
# import plotly.graph_objects as go
# import plotly.express as px
# import dash
# from dash import dcc
# from dash import html
# from dash.dependencies import Input, Output
# import requests
# import json
# import requests
# from flask import Flask
# import dash_bootstrap_components as dbc
# import dash_core_components as dcc
api_key = 'HA94TK1V286GC2BA' # Use this API key throughout the script
tickers = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD']
symbol = 'NVDA'
def get_stock_data(symbol, api_key):
ts = TimeSeries(api_key, output_format='pandas')
data, _ = ts.get_daily_adjusted(symbol=symbol, outputsize='full')
data = data.sort_index(ascending=True)
return data
data = get_stock_data(symbol, api_key)
def get_stock_data_av(tickers, api_key):
ts = TimeSeries(key=api_key, output_format='pandas')
stock_data = {}
for ticker in tickers:
data, _ = ts.get_daily_adjusted(symbol=ticker, outputsize='full')
stock_data[ticker] = data['5. adjusted close']
return stock_data
def get_moving_averages(data, window):
return data['4. close'].rolling(window=window).mean()
data['MA20'] = get_moving_averages(data, 20)
data['MA50'] = get_moving_averages(data, 50)
data['MA300'] = get_moving_averages(data, 300)
def create_candlestick_chart(data, symbol):
fig = go.Figure()
#fig.add_trace(go.Candlestick(x=data.index,
# open=data['1. open'],
# high=data['2. high'],
# low=data['3. low'],
# close=data['4. close'],
#name=symbol))
fig.add_trace(go.Scatter(x=data.index, y=data['4. close'], name='Stock Price', line=dict(color='limegreen', width=2)))
fig.add_trace(go.Scatter(x=data.index, y=data['MA20'], name='MA20', line=dict(color='lightblue', width=2)))
fig.add_trace(go.Scatter(x=data.index, y=data['MA50'], name='MA50', line=dict(color='yellow', width=2)))
fig.add_trace(go.Scatter(x=data.index, y=data['MA300'], name='MA300', line=dict(color='red', width=2)))
fig.update_layout(title=f'{symbol} Stock Price',
xaxis_title='Date',
yaxis_title='Price',
xaxis_rangeslider_visible=False,
plot_bgcolor='black',
paper_bgcolor='black',
font=dict(color='white'))
return fig
def calculate_daily_return(data):
data['daily_return'] = data['4. close'].pct_change() * 100
return data
data = calculate_daily_return(data)
# add average daily - number
def plot_daily_return(data, symbol):
fig = px.line(data.reset_index(), x='date', y='daily_return', title=f'{symbol} Daily Return')
fig.update_xaxes(title_text='Date')
fig.update_yaxes(title_text='Daily Return (%)')
fig.update_layout(title=f'{symbol} Daily Return (%)',
xaxis_title='Date',
yaxis_title='Price',
xaxis_rangeslider_visible=False,
plot_bgcolor='black',
paper_bgcolor='black',
font=dict(color='white'))
return fig # Return the figure object instead of calling fig.show()
def plot_volume(data, symbol):
fig = go.Figure()
fig.add_trace(go.Bar(x=data.index, y=data['6. volume'], name='Volume', marker=dict(color='rgba(255, 0, 0, 1)')))
fig.update_layout(title=f'{symbol} Trading Volume',
xaxis_title='Date',
yaxis_title='Volume',
plot_bgcolor='black',
paper_bgcolor='black',
font=dict(color='white'))
fig.show()
return fig
def valuation_ratios_chart(overview_data, symbol):
pe_ratio = float(overview_data['PEGRatio'])
price_to_book_ratio = float(overview_data['PriceToBookRatio'])
price_to_sales_ratio = float(overview_data['PriceToSalesRatioTTM'])
ev_to_revenue = float(overview_data['EVToRevenue'])
ev_to_ebitda = float(overview_data['EVToEBITDA'])
ratios = [pe_ratio, price_to_book_ratio, price_to_sales_ratio, ev_to_revenue, ev_to_ebitda]
labels = ['PE Ratio', 'Price to Book Ratio', 'Price to Sales Ratio', 'EV to Revenue', 'EV to EBITDA']
colors = ['blue', 'green', 'red', 'purple', 'orange']
fig = go.Figure(data=[go.Bar(x=labels, y=ratios, marker_color=colors)])
fig.update_layout(title=f'Financial Ratios for {symbol}',
xaxis_title='Company',
yaxis_title='Ratio Value',
plot_bgcolor='black',
paper_bgcolor='black')
return fig
def get_company_overview_data(symbol, api_key):
fundamental_data = FundamentalData(api_key)
overview_data, _ = fundamental_data.get_company_overview(symbol)
return overview_data
def create_revenue_chart(tickers, api_key):
fig = go.Figure()
for symbol in tickers:
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
data = json.loads(response.text)
revenues = []
for report in data['annualReports'][:5]:
revenues.append(float(report['totalRevenue']))
revenues = revenues[::-1]
years = sorted([int(data['annualReports'][i]['fiscalDateEnding'][:4]) for i in range(4, -1, -1)])
fig.add_trace(go.Scatter(x=years, y=revenues, mode='lines', name=symbol))
fig.update_layout(
title='Total Revenue (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Revenue (in billions USD)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def create_revenue_chart(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
data = json.loads(response.text)
revenues = []
for report in data['annualReports'][:5]:
revenues.append(float(report['totalRevenue']))
revenues = revenues[::-1]
years = sorted([int(data['annualReports'][i]['fiscalDateEnding'][:4]) for i in range(4, -1, -1)])
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=revenues, mode='lines',marker=dict(color='white', size=8),line=dict(color='pink')))
fig.update_layout(
title=f'{symbol} Total Revenue (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Revenue (in billions USD)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def create_gprofit_chart(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
data = json.loads(response.text)
revenues = []
for report in data['annualReports'][:5]:
revenues.append(float(report['grossProfit']))
revenues = revenues[::-1]
years = sorted([int(data['annualReports'][i]['fiscalDateEnding'][:4]) for i in range(4, -1, -1)])
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=revenues, mode='lines'))
fig.update_layout(
title=f'{symbol} Gross Profit (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Gross Profit (in billions USD)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def create_costofrevenue_chart(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
data = json.loads(response.text)
revenues = []
for report in data['annualReports'][:5]:
revenues.append(float(report['costOfRevenue']))
revenues = revenues[::-1]
years = sorted([int(data['annualReports'][i]['fiscalDateEnding'][:4]) for i in range(4, -1, -1)])
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=revenues, mode='lines'))
fig.update_layout(
title=f'{symbol} Cost of Revenue (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Cost of Revenue (in billions USD)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def create_operatingIncome_chart(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
data = json.loads(response.text)
revenues = []
for report in data['annualReports'][:5]:
revenues.append(float(report['operatingIncome']))
revenues = revenues[::-1]
years = sorted([int(data['annualReports'][i]['fiscalDateEnding'][:4]) for i in range(4, -1, -1)])
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=revenues, mode='lines'))
fig.update_layout(
title=f'{symbol} Operating Income (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Operating Income (in billions USD)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def create_operatingExpenses_chart(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
data = json.loads(response.text)
revenues = []
for report in data['annualReports'][:5]:
revenues.append(float(report['operatingExpenses']))
revenues = revenues[::-1]
years = sorted([int(data['annualReports'][i]['fiscalDateEnding'][:4]) for i in range(4, -1, -1)])
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=revenues, mode='lines',marker=dict(color='white', size=8),line=dict(color='limegreen')))
fig.update_layout(
title=f'{symbol} Operating Expenses (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Operating Expenses (in billions USD)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
import json
import requests
import plotly.graph_objects as go
from plotly.subplots import make_subplots
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD'] # Add the list of symbols you'd like to compare
def get_debt_equity_ratio(symbol, api_key, annual_data):
total_debt = float(annual_data['longTermDebt']) + float(annual_data['shortLongTermDebtTotal'])
total_equity = float(annual_data['totalShareholderEquity'])
debt_to_equity_ratio = total_debt / total_equity
return debt_to_equity_ratio
def create_debt_equity_ratio_chart(symbols, api_key):
debt_to_equity_ratios = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
calculated_de_ratio = get_debt_equity_ratio(symbol, api_key, annual_data)
debt_to_equity_ratios.append(calculated_de_ratio)
min_de_ratio = min(filter(None, debt_to_equity_ratios))
max_de_ratio = max(filter(None, debt_to_equity_ratios))
nvda_de_ratio = debt_to_equity_ratios[symbols.index('NVDA')]
subplot_fig = make_subplots(rows=1, cols=3, specs=[[{"type": "xy"}, {"type": "xy"}, {"type": "indicator"}]], subplot_titles=('Bar Chart', 'Gauge Meter'))
subplot_fig.add_trace(go.Bar(x=symbols, y=debt_to_equity_ratios, name='Bar Chart', marker_color='blue'), row=1, col=1)
subplot_fig.add_trace(go.Indicator(
mode='gauge+number',
value=nvda_de_ratio,
gauge={
'axis': {'range': [min_de_ratio, max_de_ratio]},
'bar': {'color': 'rgba(255, 255, 255, 0.5)'},
'steps': [
{'range': [min_de_ratio, nvda_de_ratio], 'color': 'deepskyblue'},
{'range': [nvda_de_ratio, max_de_ratio], 'color': 'lightgray'}
]
},
domain={'row': 0, 'column': 2},
title={'text': 'NVDA Debt-to-Equity Ratio'}),
row=1, col=3)
subplot_fig.update_layout(
title='Debt-to-Equity Ratio (Comparing Companies)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
subplot_fig.update_xaxes(title_text='Symbols', row=1, col=1)
subplot_fig.update_yaxes(title_text='Debt-to-Equity Ratio', row=1, col=1)
return subplot_fig
def create_current_ratio_chart(symbol,api_key):
# set the endpoint URL and parameters
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
# send a GET request to the API endpoint
response = requests.get(url)
# parse the JSON data from the API response
data = json.loads(response.text)
# extract the total current asset and total current liability data from the API response for the past 5 years
asset_data = []
liability_data = []
for report in data['annualReports'][:5]:
total_current_Assets = float(report['totalCurrentAssets']) if report['totalCurrentAssets'] != 'None' else 0
total_current_Liabilities = float(report['totalCurrentLiabilities']) if report['totalCurrentLiabilities'] != 'None' else 0
asset_data.append(total_current_Assets)
liability_data.append(total_current_Liabilities)
# calculate the debt-to-equity ratio
current_ratio = [ asset/ liability if asset != 0 else 0 for asset, liability in zip(asset_data, liability_data)]
# reverse the data to plot it in chronological order
current_ratio = current_ratio[::-1]
# create a list of years for the x-axis
years = [str(int(data['annualReports'][i]['fiscalDateEnding'][:4])) for i in range(4, -1, -1)]
# create a Plotly figure object
fig = go.Figure()
# add a line trace for the debt-to-equity data
fig.add_trace(go.Scatter(x=years, y=current_ratio, mode='lines'))
# update the figure layout
fig.update_layout(
title=f'{symbol} Current Ratio (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Current Ratio',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
# import requests
# import json
# import plotly.graph_objects as go
# def create_quick_ratio_chart(symbols, api_key):
# # create a list to store the data for each company
# data_list = []
# # loop through each company symbol
# for symbol in symbols:
# # set the endpoint URL and parameters
# url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
# # send a GET request to the API endpoint
# response = requests.get(url)
# # parse the JSON data from the API response
# data = json.loads(response.text)
# # extract the total current asset and total current liability data from the API response for the past 5 years
# asset_data = []
# liability_data = []
# inventory_data =[]
# for report in data['annualReports'][:5]:
# total_current_Assets = float(report['totalCurrentAssets']) if report['totalCurrentAssets'] != 'None' else 0
# total_current_Liabilities = float(report['totalCurrentLiabilities']) if report['totalCurrentLiabilities'] != 'None' else 0
# total_inventory = float(report['inventory']) if report['inventory'] != 'None' else 0
# asset_data.append(total_current_Assets)
# liability_data.append(total_current_Liabilities)
# inventory_data.append(total_inventory)
# # calculate the quick ratio
# quick_ratio = [(asset - inventory) / liability if liability != 0 else 0 for asset, inventory, liability in zip(asset_data, inventory_data, liability_data)]
# # reverse the data to plot it in chronological order
# quick_ratio = quick_ratio[::-1]
# # calculate the minimum, maximum, and NVDA quick ratio values for the gauge meter
# min_ratio = min(quick_ratio)
# max_ratio = max(quick_ratio)
# nvda_ratio = quick_ratio[0]
# # # append the data to the data_list
# data_list.append({'symbol': symbol, 'quick_ratio': quick_ratio, 'min_ratio': min_ratio, 'max_ratio': max_ratio, 'nvda_ratio': nvda_ratio})
# # # create a list of years for the x-axis
# years = [str(int(data['annualReports'][i]['fiscalDateEnding'][:4])) for i in range(4, -1, -1)]
# # create a Plotly figure object with a grid layout
# fig = go.Figure()
# # # add a bar trace for the quick ratio data for each company
# for data in data_list:
# fig.add_trace(go.Bar(name=data['symbol'], x=years, y=data['quick_ratio']))
# # # add a gauge meter trace for the NVDA quick ratio
# fig.add_trace(
# go.Indicator(
# mode='gauge+number',
# value=data_list[0]['nvda_ratio'],
# title={'text': f"{data_list[0]['symbol']} Quick Ratio ({years[0]})"},
# gauge={
# 'axis': {'range': [data_list[0]['min_ratio'], data_list[0]['max_ratio']]},
# 'steps': [
# {'range': [data_list[0]['min_ratio'], data_list[0]['nvda_ratio']], 'color': 'red'},
# {'range': [data_list[0]['nvda_ratio'], data_list[0]['max_ratio']], 'color': 'green'}
# ],
# 'threshold': {
# 'line': {'color': "white", 'width': 4},
# 'thickness': 0.75,
# 'value': 0
# }
# }
# ))
# fig.update_layout(
# plot_bgcolor='black',
# paper_bgcolor='black',
# font=dict(color='white')
# )
# return fig
fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'bar'}, {'type': 'indicator'}]], column_widths=[0.7, 0.3])
fig.add_trace(
go.Bar(
x=[data['symbol']],
y=[data['quick_ratio']],
name='Quick ratio'
),
row=1,
col=1
)
# create a gauge meter for the NVDA quick ratio
fig.add_trace(
go.Indicator(
mode='gauge+number',
value=nvda_ratio,
title={'text': "Quick Ratio (NVDA)"},
gauge={
'axis': {'range': [min_ratio, max_ratio]},
'steps': [
{'range': [min_ratio, nvda_ratio], 'color': 'red'},
{'range': [nvda_ratio, max_ratio], 'color': 'green'}
],
'threshold': {
'line': {'color': "white", 'width': 4},
'thickness': 0.75,
'value': nvda_ratio
}
}
),
row=1,
col=2
)
# update the layout
fig.update_layout(
title='Quick Ratio for NVDA, AVGO, TXN, QCOM, and AMD (Latest Fiscal Year)',
xaxis_title='Symbols',
yaxis_title='Quick Ratio',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1721177955.py", line 85 fig.add_trace( ^ SyntaxError: invalid non-printable character U+00A0
def create_asset_turnover_chart(symbol,api_key):
# set the endpoint URL and parameters
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
# send a GET request to the API endpoint
response = requests.get(url)
# parse the JSON data from the API response
data = json.loads(response.text)
# extract the total current asset data from the API response for the past 5 years
total_asset_data = []
for report in data['annualReports'][:5]:
total_asset = float(report['totalAssets']) if report['totalAssets'] != 'None' else 0
total_asset_data.append(total_asset)
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
# send a GET request to the API endpoint
response2 = requests.get(url)
# parse the JSON data from the API response
data2 = json.loads(response2.text)
revenues = []
for report in data2['annualReports'][:5]:
revenues.append(float(report['totalRevenue']))
# calculate the asset turnover ratio
asset_turnover_ratio = [asset / revenue if revenue != 0 else 0 for asset, revenue in zip(total_asset_data, revenues)]
# reverse the data to plot it in chronological order
asset_turnover_ratio = asset_turnover_ratio[::-1]
# create a list of years for the x-axis
years = [str(int(data['annualReports'][i]['fiscalDateEnding'][:4])) for i in range(4, -1, -1)]
# create a Plotly figure object
fig = go.Figure()
# add a line trace for the asset turnover ratio
fig.add_trace(go.Scatter(x=years, y=asset_turnover_ratio, mode='lines'))
# update the figure layout
fig.update_layout(
title=f'{symbol} Asset Turnover Ratio (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Asset Turnover Ratio',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def create_shares_outstanding_chart(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
data = json.loads(response.text)
shares_outstanding = []
for report in data['annualReports'][:5]:
shares_outstanding.append(float(report['commonStockSharesOutstanding']))
shares_outstanding = shares_outstanding[::-1]
years = sorted([int(data['annualReports'][i]['fiscalDateEnding'][:4]) for i in range(4, -1, -1)])
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=shares_outstanding, mode='lines'))
fig.update_layout(
title=f'{symbol} shares_outstanding (Past 5 Years)',
xaxis_title='Year',
yaxis_title='shares_outstanding',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def get_enterprise_value(symbol, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
market_cap = float(data2['MarketCapitalization']) if data2['MarketCapitalization'] != 'None' else 0
total_debt = float(annual_data['shortLongTermDebtTotal'])
cash_and_cash_equivalents = float(annual_data['cashAndCashEquivalentsAtCarryingValue'])
enterprise_value = market_cap + total_debt - cash_and_cash_equivalents
return enterprise_value
def create_enterprise_value_chart(symbol, api_key):
enterprise_values = []
years = []
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
for i in range(5):
annual_data = balance_sheet_data['annualReports'][i]
enterprise_value = get_enterprise_value(symbol, api_key, annual_data)
enterprise_values.append(enterprise_value)
year = int(annual_data['fiscalDateEnding'][:4])
years.append(year)
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=enterprise_values, mode='lines'))
fig.update_layout(
title=f'{symbol} Enterprise Value (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Enterprise Value (in billions USD)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def get_book_ratio(symbol, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
book_value = float(data2['BookValue']) if data2['BookValue'] != 'None' else 0
total_assets = float(annual_data['totalAssets'])
total_liabilities = float(annual_data['totalLiabilities'])
common_stock = float(annual_data['commonStock'])
calculated_book_value_ratio = (total_assets-total_liabilities) / common_stock
return calculated_book_value_ratio
def create_get_book_ratio_chart(symbol, api_key):
book_value_ratios = []
years = []
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
for i in range(5):
annual_data = balance_sheet_data['annualReports'][i]
calculated_book_value_ratio = get_book_ratio(symbol, api_key, annual_data)
book_value_ratios.append(calculated_book_value_ratio )
year = int(annual_data['fiscalDateEnding'][:4])
years.append(year)
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=book_value_ratios, mode='lines'))
fig.update_layout(
title=f'{symbol} Book Value per share (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Book Value per share',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
def calculate_revenue_change_percentage(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
income_statement_data = json.loads(response.text)
current_year_revenue = float(income_statement_data['annualReports'][0]['totalRevenue'])
previous_year_revenue = float(income_statement_data['annualReports'][1]['totalRevenue'])
revenue_change_percentage = ((current_year_revenue - previous_year_revenue) / previous_year_revenue) * 100
return revenue_change_percentage
import plotly.graph_objects as go
def create_revenue_change_gauge(symbol, api_key):
revenue_change_percentage = calculate_revenue_change_percentage(symbol, api_key)
fig = go.Figure(go.Indicator(
mode='gauge+number+delta',
value=revenue_change_percentage,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': f'{symbol} Revenue Growth (Current Year vs Previous Year)', 'font': {'size': 24}},
delta={'reference': 0, 'increasing': {'color': 'green'}, 'decreasing': {'color': 'red'}},
gauge={
'axis': {'range': [None, 100], 'tickwidth': 1, 'tickcolor': 'darkblue'},
'bar': {'color': 'darkblue'},
'bgcolor': 'white',
'borderwidth': 2,
'bordercolor': 'gray',
'steps': [
{'range': [0, 50], 'color': 'cyan'},
{'range': [50, 75], 'color': 'royalblue'}
],
'threshold': {
'line': {'color': 'red', 'width': 4},
'thickness': 0.75,
'value': 0
}
}
))
fig.update_layout(
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
def calculate_profit_change_percentage(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
income_statement_data = json.loads(response.text)
current_year_profit = float(income_statement_data['annualReports'][0]['grossProfit'])
previous_year_profit = float(income_statement_data['annualReports'][1]['grossProfit'])
profit_change_percentage = ((current_year_profit - previous_year_profit) / previous_year_profit) * 100
return profit_change_percentage
def create_profit_change_gauge(symbol, api_key):
profit_change_percentage = calculate_profit_change_percentage(symbol, api_key)
fig = go.Figure(go.Indicator(
mode='gauge+number+delta',
value=profit_change_percentage,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': f'{symbol} Gross Profit Change (Current Year vs Previous Year)', 'font': {'size': 24}},
delta={'reference': 0, 'increasing': {'color': 'green'}, 'decreasing': {'color': 'red'}},
gauge={
'axis': {'range': [None, 100], 'tickwidth': 1, 'tickcolor': 'darkblue'},
'bar': {'color': 'white'},
'bgcolor': 'black',
'borderwidth': 2,
'bordercolor': 'gray',
'steps': [
{'range': [0, 50], 'color': 'blue'},
{'range': [50, 75], 'color': 'royalblue'}
],
'threshold': {
'line': {'color': 'red', 'width': 4},
'thickness': 0.75,
'value': 0
}
}
))
fig.update_layout(
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
def create_profit_change_gauge(symbol, api_key):
profit_change_percentage = calculate_profit_change_percentage(symbol, api_key)
fig = go.Figure(go.Indicator(
mode='gauge+number+delta',
value=profit_change_percentage,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': f'{symbol} Gross Profit Change (Current Year vs Previous Year)', 'font': {'size': 24}},
delta={'reference': 0, 'increasing': {'color': 'green'}, 'decreasing': {'color': 'red'}},
gauge={
'axis': {'range': [None, 100], 'tickwidth': 1, 'tickcolor': 'darkblue'},
'bar': {'color': 'darkblue'},
'bgcolor': 'white',
'borderwidth': 2,
'bordercolor': 'gray',
'steps': [
{'range': [0, 50], 'color': 'blue'},
{'range': [50, 75], 'color': 'royalblue'}
],
'threshold': {
'line': {'color': 'red', 'width': 4},
'thickness': 0.75,
'value': 0
}
}
))
fig.update_layout(
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
def create_operating_profit_chart(symbol, api_key):
operating_profits = []
years = []
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
income_statement_data = json.loads(response.text)
for i in range(5):
gross_profit = float(income_statement_data['annualReports'][i]['grossProfit'])
operating_expenses = float(income_statement_data['annualReports'][i]['operatingExpenses'])
operating_profit = gross_profit - operating_expenses
operating_profits.append(operating_profit)
year = int(income_statement_data['annualReports'][i]['fiscalDateEnding'][:4])
years.append(year)
data = {'Year': years, 'Operating Profit': operating_profits}
fig = px.bar(data, x='Year', y='Operating Profit', text='Operating Profit', labels={'Operating Profit': f'{symbol} Operating Profit'},
color='Operating Profit', color_continuous_scale='Bluered_r')
fig.update_layout(
title=f'{symbol} Operating Profit (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Operating Profit',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
def get_return_on_asset2(symbol, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
net_income = float(data2['annualReports'][0]['netIncome']) if data2['annualReports'][0]['netIncome'] != 'None' else 0
total_assets = float(annual_data['totalAssets'])
calculated_roa_ratio = net_income / total_assets
return calculated_roa_ratio
def create_get_return_on_asset2(symbol, api_key):
roa_ratios = []
years = []
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
for i in range(5):
annual_data = balance_sheet_data['annualReports'][i]
calculated_roa_ratio = get_return_on_asset2(symbol, api_key, annual_data)
roa_ratios.append(calculated_roa_ratio)
year = int(annual_data['fiscalDateEnding'][:4])
years.append(year)
fig = go.Figure()
fig.add_trace(go.Scatter(x=years, y=roa_ratios, mode='lines',name='Line Chart'))
fig.add_trace(go.Bar(x=years, y=roa_ratios, name='Bar Chart', marker_color = 'pink'))
fig.update_layout(
title=f'{symbol} Return on Asset (Past 5 Years)',
xaxis_title='Year',
yaxis_title='Return on Asset ratio',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black',
xaxis=dict(
tickmode='linear', # Set tickmode to linear
dtick=1, # Set the interval between ticks to 1 year
tickformat='d' # Display the tick labels as integers
)
)
return fig
import requests
import json
import plotly.graph_objs as go
from plotly.subplots import make_subplots
def get_return_on_equity(symbol, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
net_income = float(data2['annualReports'][0]['netIncome']) if data2['annualReports'][0]['netIncome'] != 'None' else 0
common_stock = float(annual_data['totalShareholderEquity'])
if common_stock == 0:
calculated_roe_ratio = None
else:
calculated_roe_ratio = net_income / common_stock
return calculated_roe_ratio
def create_get_return_on_equity(symbols, api_key):
roe_ratios = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
calculated_roe_ratio = get_return_on_equity(symbol, api_key, annual_data)
roe_ratios.append(calculated_roe_ratio)
nvda_ratio = roe_ratios[symbols.index('NVDA')]
min_ratio = min(roe_ratios)
mode_ratio = max(set(roe_ratios), key=roe_ratios.count)
# Create the bar chart subplot
fig = make_subplots(rows=1, cols=2, column_widths=[0.67, 0.33])
fig.add_trace(
go.Bar(x=symbols, y=roe_ratios, name='Return on Equity Ratio', marker_color ='purple'),
row=1, col=1
)
# # Create the bullet gauge chart subplot
# fig.add_trace(
# go.Bar(x=['NVDA'], y=[nvda_ratio], name='NVDA Ratio', marker_color ='red'),
# row=1, col=2
# )
fig.add_trace(
go.Indicator(
domain={'x': [0.7, 1], 'y': [0, 1]},
mode="gauge+number",
value=nvda_ratio,
title={'text': "<b>Return on Equity Ratio</b><br><span style='font-size:0.8em;color:gray'>Last Fiscal Year</span>"},
gauge={
'axis': {'range': [min_ratio, max(roe_ratios)], 'tickwidth': 1, 'tickcolor': "darkblue"},
'bar': {'color': "darkblue"},
'bgcolor': "white",
'steps': [
{'range': [min_ratio, mode_ratio], 'color': 'white'},
{'range': [mode_ratio, max(roe_ratios)], 'color': 'lightblue'}
],
'threshold': {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': nvda_ratio}
}
)
)
fig.update_layout(
title='Return on Equity',
yaxis_title='Return on Equity Ratio',
template='plotly_dark',
plot_bgcolor='black',
width=750 # Set the overall chart width to 750 pixels
)
return fig
############# RETURN ON ASSET
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD'] # Add the list of symbols you'd like to compare
def get_return_on_asset(symbols, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbols}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
net_income = float(data2['annualReports'][0]['netIncome']) if data2['annualReports'][0]['netIncome'] != 'None' else 0
total_assets = float(annual_data['totalAssets'])
if total_assets == 0:
calculated_roa_ratio = None
else:
calculated_roa_ratio = net_income / total_assets
return calculated_roa_ratio
def create_get_return_on_asset(symbols, api_key):
roa_ratios = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
calculated_roa_ratio = get_return_on_asset(symbol, api_key, annual_data)
roa_ratios.append(calculated_roa_ratio)
min_ratio = min(roa_ratios)
max_ratio = max(roa_ratios)
mode_ratio = max(set(roa_ratios), key=roa_ratios.count)
nvda_ratio = roa_ratios[symbols.index('NVDA')]
# Create the bar chart subplot
fig = make_subplots(rows=1, cols=2, column_widths=[0.67, 0.33])
fig.add_trace(
go.Bar(x=symbols, y=roa_ratios, name='Return on Assets', marker_color ='purple'),
row=1, col=1
)
# # Create the bullet gauge chart subplot
# fig.add_trace(
# go.Bar(x=['NVDA'], y=[nvda_ratio], name='NVDA Ratio', marker_color ='red'),
# row=1, col=2
# )
fig.add_trace(
go.Indicator(
domain={'x': [0.7, 1], 'y': [0, 1]},
mode="gauge+number",
value=nvda_ratio,
title={'text': "<b>Return on Assets</b><br><span style='font-size:0.8em;color:gray'>Last Fiscal Year</span>"},
gauge={
'axis': {'range': [min_ratio, max(roa_ratios)], 'tickwidth': 1, 'tickcolor': "darkblue"},
'bar': {'color': "darkblue"},
'bgcolor': "white",
'steps': [
{'range': [min_ratio, mode_ratio], 'color': 'white'},
{'range': [mode_ratio, max(roa_ratios)], 'color': 'lightblue'}
],
'threshold': {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': nvda_ratio}
}
)
)
fig.update_layout(
title='Return on Assets',
yaxis_title='Return on Assets',
template='plotly_dark',
plot_bgcolor='black',
width=750 # Set the overall chart width to 750 pixels
)
# fig = go.Figure()
# fig.add_trace(
# go.Bar(x=symbols, y=roa_ratios, name='Return on Asset Ratio', marker_color='grey')
# )
# fig.add_trace(
# go.Indicator(
# mode="gauge+number",
# gauge={
# "axis": {"range": [min_ratio, max_ratio]},
# "bar": {"color": "darkblue"},
# "steps": [
# {"range": [min_ratio, nvda_ratio], "color": "lightblue"},
# {"range": [nvda_ratio, max_ratio], "color": "blue"}
# ],
# "threshold": {"line": {"color": "red", "width": 4}, "value": nvda_ratio}
# },
# number={"prefix": "ROA:0.106 ", "valueformat": ".2f", "font": {"size": 30}},
# value=0
# )
# )
# fig.update_layout(
# title='Return on Asset',
# template='plotly_dark',
# plot_bgcolor='black',
# paper_bgcolor='black'
# )
return fig
########GROSS
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD'] # Add the list of symbols you'd like to compare
import requests
import json
import plotly.graph_objs as go
from plotly.subplots import make_subplots
def get_gross_profit(symbol, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
gross_profit = float(data2['annualReports'][0]['grossProfit']) if data2['annualReports'][0]['grossProfit'] != 'None' else 0
return gross_profit
def create_get_gross_profit(symbols, api_key):
gross_profits = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
income_statement_data = json.loads(response.text)
annual_data = income_statement_data['annualReports'][0] # Get the most recent annual data
gross_profit = get_gross_profit(symbol, api_key, annual_data)
gross_profits.append(gross_profit)
min_profit = min(gross_profits)
max_profit = max(gross_profits)
nvda_profit = gross_profits[symbols.index('NVDA')]
# Create the subplots with a bar chart on the left and a gauge chart on the right
fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'bar'}, {'type': 'indicator'}]], column_widths=[2/3, 1/3], subplot_titles=('Gross Profit', 'NVDA Gross Profit'))
# Add the bar chart to the left subplot
fig.add_trace(go.Bar(x=symbols, y=gross_profits, name='Gross Profit', marker_color='green', hovertemplate='%{y:.2f}'), row=1, col=1)
# Add the gauge chart to the right subplot
fig.add_trace(
go.Indicator(
domain={'x': [0, 0.4], 'y': [0.2, 0.8]},
mode="gauge+number",
value=nvda_profit,
title={'text': "<b>NVDA Gross Profit</b><br><span style='font-size:0.8em;color:gray'>Last Fiscal Year</span>"},
gauge={
'axis': {'range': [min_profit, max_profit], 'tickwidth': 1, 'tickcolor': "darkblue"},
'bar': {'color': "darkblue"},
'bgcolor': "white",
'steps': [
{'range': [min_profit, nvda_profit], 'color': 'white'},
{'range': [nvda_profit, max_profit], 'color': 'lightgreen'}],
'threshold': {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': nvda_profit}
}
), row=1, col=2
)
fig.update_layout(
title='Gross Profit',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
fig.update_xaxes(title_text='Symbols', row=1, col=1)
fig.update_yaxes(title_text='Gross Profit', row=1, col=1)
return fig
import json
import requests
import plotly.graph_objects as go
from plotly.subplots import make_subplots
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD'] # Add the list of symbols you'd like to compare
def get_operating_margin(symbol, api_key, annual_data):
operating_income = float(annual_data['operatingIncome']) if annual_data['operatingIncome'] != 'None' else 0
total_revenue = float(annual_data['totalRevenue'])
if operating_income == 0:
calculated_operating_margin = None
else:
calculated_operating_margin = operating_income / total_revenue
return calculated_operating_margin
def create_get_operating_margin(symbols, api_key):
operating_margin = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
income_statement_data = json.loads(response.text)
if 'annualReports' not in income_statement_data:
operating_margin.append(None)
continue
annual_data = income_statement_data['annualReports'][0] # Get the most recent annual data
calculated_operating_margin = get_operating_margin(symbol, api_key, annual_data)
operating_margin.append(calculated_operating_margin)
min_margin = min(filter(None, operating_margin))
max_margin = max(filter(None, operating_margin))
nvda_margin = operating_margin[symbols.index('NVDA')]
fig = make_subplots(rows=1, cols=2, column_widths=[2/3, 1/3], specs=[[{"type": "bar"}, {"type": "indicator"}]], subplot_titles=('Bar Chart', 'Graduated Bar Plot'))
fig.add_trace(go.Bar(x=symbols, y=operating_margin, name='Bar Chart'), row=1, col=1)
fig.add_trace(go.Indicator(
mode = "gauge+number",
value = nvda_margin,
domain = {'x': [0, 1], 'y': [0.2, 0.8]},
title = {'text': "NVDA Operating Margin"},
gauge = {'axis': {'range': [None, max_margin]},
'bar': {'color': "darkblue"},
'steps' : [{'range': [min_margin, max_margin/3], 'color': 'red'},
{'range': [max_margin/3, 2*max_margin/3], 'color': 'yellow'},
{'range': [2*max_margin/3, max_margin], 'color': 'green'}],
'threshold' : {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': nvda_margin}}),
row=1, col=2)
fig.update_layout(
title='Operating Margin (Comparing Companies)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
fig.update_xaxes(title_text='Symbols', row=1, col=1)
fig.update_yaxes(title_text='Operating Margin', row=1, col=1)
return fig
import json
import requests
import plotly.graph_objects as go
from plotly.subplots import make_subplots
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD'] # Add the list of symbols you'd like to compare
def get_net_profit_margin(symbol, api_key, annual_data):
net_income = float(annual_data['netIncome']) if annual_data['netIncome'] != 'None' else 0
total_revenue = float(annual_data['totalRevenue'])
if net_income == 0:
calculated_net_profit_margin = None
else:
calculated_net_profit_margin = net_income / total_revenue
return calculated_net_profit_margin
def create_get_net_profit_margin(symbols, api_key):
net_profit_margin = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
income_statement_data = json.loads(response.text)
if 'annualReports' not in income_statement_data:
net_profit_margin.append(None)
continue
annual_data = income_statement_data['annualReports'][0] # Get the most recent annual data
calculated_net_profit_margin = get_net_profit_margin(symbol, api_key, annual_data)
net_profit_margin.append(calculated_net_profit_margin)
min_margin = min(filter(None, net_profit_margin))
max_margin = max(filter(None, net_profit_margin))
nvda_margin = net_profit_margin[symbols.index('NVDA')]
subplot_fig = make_subplots(rows=1, cols=3, specs=[[{"type": "xy"}, {"type": "xy"}, {"type": "indicator"}]], subplot_titles=('Bar Chart', 'Gauge Meter'))
subplot_fig.add_trace(go.Bar(x=symbols, y=net_profit_margin, name='Bar Chart'), row=1, col=1)
subplot_fig.add_trace(go.Indicator(
mode='gauge+number',
value=nvda_margin,
gauge={
'axis': {'range': [min_margin, max_margin]},
'bar': {'color': 'rgba(255, 255, 255, 0.5)'},
'steps': [
{'range': [min_margin, nvda_margin], 'color': 'cyan'},
{'range': [nvda_margin, max_margin], 'color': 'lightgray'}
]
},
domain={'row': 0, 'column': 2},
title={'text': 'NVDA Net Profit Margin'}),
row=1, col=3)
subplot_fig.update_layout(
title='Net Profit Margin (Comparing Companies)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
subplot_fig.update_xaxes(title_text='Symbols', row=1, col=1)
subplot_fig.update_yaxes(title_text='Net Profit Margin', row=1, col=1)
return subplot_fig
import json
import requests
import plotly.graph_objects as go
from plotly.subplots import make_subplots
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD'] # Add the list of symbols you'd like to compare
def get_earnings_per_share(symbol, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
net_income = float(data2['annualReports'][0]['netIncome']) if data2['annualReports'][0]['netIncome'] != 'None' else 0
shares_outstanding = float(annual_data['commonStockSharesOutstanding'])
if shares_outstanding == 0:
calculated_eps_ratio = None
else:
calculated_eps_ratio = net_income / shares_outstanding
return calculated_eps_ratio
def create_get_earnings_per_share(symbols, api_key):
eps_ratios = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
calculated_eps_ratio = get_earnings_per_share(symbol, api_key, annual_data)
eps_ratios.append(calculated_eps_ratio)
min_eps = min(filter(None, eps_ratios))
max_eps = max(filter(None, eps_ratios))
nvda_eps = eps_ratios[symbols.index('NVDA')]
subplot_fig = make_subplots(rows=1, cols=3, specs=[[{"type": "xy"}, {"type": "xy"}, {"type": "indicator"}]], subplot_titles=('Bar Chart', 'Gauge Meter'))
subplot_fig.add_trace(go.Bar(x=symbols, y=eps_ratios, name='Bar Chart', marker_color ='green'), row=1, col=1)
subplot_fig.add_trace(go.Indicator(
mode='gauge+number',
value=nvda_eps,
gauge={
'axis': {'range': [min_eps, max_eps]},
'bar': {'color': 'rgba(255, 255, 255, 0.5)'},
'steps': [
{'range': [min_eps, nvda_eps], 'color': 'lime'},
{'range': [nvda_eps, max_eps], 'color': 'lightgray'}
]
},
domain={'row': 0, 'column': 2},
title={'text': 'NVDA Earnings Per Share'}),
row=1, col=3)
subplot_fig.update_layout(
title='EPS (Comparing Companies)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
subplot_fig.update_xaxes(title_text='Symbols', row=1, col=1)
subplot_fig.update_yaxes(title_text='EPS', row=1, col=1)
return subplot_fig
import requests
import json
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def get_market_book_value(data):
market_value = float(data['MarketCapitalization']) if data['MarketCapitalization'] != 'None' else 0
book_value = float(data['BookValue'])
if market_value == 0:
calculated_market_book_value = None
else:
calculated_market_book_value = market_value / book_value # divide per share
return calculated_market_book_value
def create_get_market_book_value(symbols, api_key):
market_book_value = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
data = json.loads(response.text)
calculated_market_book_value = get_market_book_value(data)
market_book_value.append(calculated_market_book_value)
# calculate the minimum, maximum, and NVDA market/book value for the gauge meter
min_value = min(market_book_value)
max_value = max(market_book_value)
nvda_value = market_book_value[symbols.index('NVDA')]
# create a Plotly figure object with a grid layout
fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'bar'}, {'type': 'indicator'}]])
# add a bar trace for the market/book value data
fig.add_trace(go.Bar(x=market_book_value, y=symbols, name='Market/Book Value', marker_color='orange', orientation='h'),
row=1, col=1)
# add a gauge meter trace for the NVDA market/book value
fig.add_trace(
go.Indicator(
mode='gauge+number',
value=nvda_value,
title={'text': f"NVDA Market/Book Value"},
gauge={
'axis': {'range': [min_value, max_value]},
'steps': [
{'range': [min_value, nvda_value], 'color': 'red'},
{'range': [nvda_value, max_value], 'color': 'green'}
],
'threshold': {
'line': {'color': "white", 'width': 4},
'thickness': 0.75,
'value': nvda_value
}
}
),
row=1, col=2
)
# update the figure layout
fig.update_layout(
title='Market vs Book Value (Comparing Companies)',
xaxis_title='Market/Book Value',
yaxis_title='Symbols',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
import json
import requests
import plotly.graph_objects as go
from plotly.subplots import make_subplots
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD'] # Add the list of symbols you'd like to compare
def get_company_overview_data(symbol, api_key):
url = f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
overview_data = json.loads(response.text)
return overview_data
def get_beta_values(symbols, api_key):
beta_values = {}
for symbol in symbols:
overview_data = get_company_overview_data(symbol, api_key)
beta_values[symbol] = float(overview_data['Beta'])
return beta_values
def plot_beta_comparison(beta_values):
# Calculate min, max, and NVDA beta values
min_beta = min(beta_values.values())
max_beta = max(beta_values.values())
nvda_beta = beta_values.get('NVDA', None)
# Create the bar chart subplot
fig = make_subplots(rows=1, cols=2, column_widths=[0.7, 0.3], specs=[[{"type": "xy"}, {"type": "indicator"}]])
fig.add_trace(
go.Bar(x=list(beta_values.keys()), y=list(beta_values.values()), name='Beta',
marker=dict(color=list(beta_values.values()), colorscale='Viridis', showscale=True),
orientation='h'), row=1, col=1)
# Create the bullet gauge chart subplot
fig.add_trace(
go.Indicator(
domain={'x': [0.7, 1], 'y': [0, 1]},
mode="gauge+number",
value=nvda_beta,
title={'text': "<b>NVDA Beta Value</b><br><span style='font-size:0.8em;color:gray'>Beta Comparison</span>"},
gauge={
'axis': {'range': [min_beta, max_beta], 'tickwidth': 1, 'tickcolor': "darkblue"},
'bar': {'color': "darkblue"},
'bgcolor': "white",
'steps': [
{'range': [min_beta, nvda_beta], 'color': 'white'},
{'range': [nvda_beta, max_beta], 'color': 'lightblue'}],
'threshold': {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': nvda_beta}
}
), row=1, col=2)
fig.update_layout(
title='Beta Comparison',
xaxis_title='Company',
yaxis_title='Beta Value',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black')
return fig
# Get daily return data for multiple companies
def get_daily_return_data(symbols, api_key):
daily_returns = pd.DataFrame()
for symbol in symbols:
ts = TimeSeries(api_key, output_format='pandas')
data, _ = ts.get_daily_adjusted(symbol=symbol, outputsize='full')
data['daily_return'] = data['4. close'].pct_change()
data['symbol'] = symbol
daily_returns = pd.concat([daily_returns, data[['daily_return', 'symbol']]], axis=0)
return daily_returns
# Calculate standard deviation of daily return for multiple companies
def get_std_return_data(symbols, api_key):
daily_returns = get_daily_return_data(symbols, api_key)
std_returns = daily_returns.groupby('symbol')['daily_return'].std().reset_index()
return std_returns
# Plot standard deviation of daily return for multiple companies
def plot_std_return_data(std_returns):
fig = go.Figure()
fig.add_trace(go.Bar(x=std_returns['symbol'], y=std_returns['daily_return'], name='Standard Deviation'))
fig.update_layout(title='Standard Deviation of Daily Return',
xaxis_title='Company',
yaxis_title='Standard Deviation',
plot_bgcolor='black',
paper_bgcolor='black')
return fig
import json
import requests
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def get_inventory_turnover(symbol, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
COGS = 0
if 'annualReports' in data2 and len(data2['annualReports']) > 0:
COGS = float(data2['annualReports'][0]['costOfRevenue']) if data2['annualReports'][0]['costOfRevenue'] != 'None' else 0
inventory = float(annual_data['inventory'])
if COGS == 0:
calculated_inventory_turnover = None
else:
calculated_inventory_turnover = COGS / inventory
return calculated_inventory_turnover
def create_get_inventory_turnover(symbols, api_key):
inventory_turnover = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
calculated_inventory_turnover = get_inventory_turnover(symbol, api_key, annual_data)
inventory_turnover.append(calculated_inventory_turnover)
min_inventory_turnover = min(filter(None, inventory_turnover))
max_inventory_turnover = max(filter(None, inventory_turnover))
nvda_inventory_turnover = inventory_turnover[symbols.index('NVDA')]
subplot_fig = make_subplots(rows=1, cols=3, specs=[[{"type": "xy"}, {"type": "xy"}, {"type": "indicator"}]], subplot_titles=('Bar Chart', 'Gauge Meter'))
subplot_fig.add_trace(go.Bar(x=symbols, y=inventory_turnover, name='Bar Chart', marker_color ='green'), row=1, col=1)
subplot_fig.add_trace(go.Indicator(
mode='gauge+number',
value=nvda_inventory_turnover,
gauge={
'axis': {'range': [min_inventory_turnover, max_inventory_turnover]},
'bar': {'color': 'rgba(255, 255, 255, 0.5)'},
'steps': [
{'range': [min_inventory_turnover, nvda_inventory_turnover], 'color': 'lime'},
{'range': [nvda_inventory_turnover, max_inventory_turnover], 'color': 'lightgray'}
]
},
domain={'row': 0, 'column': 2},
title={'text': 'NVDA Inventory Turnover'}),
row=1, col=3)
subplot_fig.update_layout(
title='Inventory Turnover (Comparing Companies)',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
subplot_fig.update_xaxes(title_text='Symbols', row=1, col=1)
subplot_fig.update_yaxes(title_text='Inventory Turnover', row=1, col=1)
return subplot_fig
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD'] # Add the list of symbols you'd like to compare
def get_asset_turnover(symbols, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbols}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
revenue = float(data2['annualReports'][0]['totalRevenue']) if data2['annualReports'][0]['totalRevenue'] != 'None' else 0
asset = float(annual_data['totalAssets'])
if revenue == 0:
calculated_asset_ratio = None
else:
calculated_asset_ratio = revenue / asset
return calculated_asset_ratio
def create_get_asset_turnover(symbols, api_key):
asset_ratios = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
calculated_asset_ratio = get_asset_turnover(symbol, api_key, annual_data)
asset_ratios.append(calculated_asset_ratio)
fig = go.Figure()
fig.add_trace(go.Bar(x=asset_ratios, y=symbols, name='Bar Chart',
marker=dict(color=asset_ratios, colorscale='Viridis', showscale=True),
orientation='h'))
fig.update_layout(
title='Asset Turnover(Comparing Companies)',
xaxis_title='Symbols',
yaxis_title='Asset Turnover',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
import plotly.graph_objs as go
def get_asset_turnover_candle(symbol, api_key, annual_data):
url2 = f'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol={symbol}&apikey={api_key}'
response2 = requests.get(url2)
data2 = json.loads(response2.text)
revenue = float(data2['annualReports'][0]['totalRevenue']) if data2['annualReports'][0]['totalRevenue'] != 'None' else 0
asset = float(annual_data['totalAssets'])
if revenue == 0:
calculated_asset_ratio = None
else:
calculated_asset_ratio = revenue / asset
return calculated_asset_ratio
def create_get_asset_turnover_candle(symbols, api_key):
asset_ratios = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
calculated_asset_ratio = get_asset_turnover(symbol, api_key, annual_data)
asset_ratios.append(calculated_asset_ratio)
fig = go.Figure()
fig.add_trace(go.Bar(x=symbols, y=asset_ratios, name='Asset Turnover',
marker=dict(color=asset_ratios, colorscale='Viridis', showscale=True),
orientation='h'))
fig.add_trace(go.Indicator(
domain={'x': [0.8, 1], 'y': [0, 1]},
value=asset_ratios[-1],
mode="gauge+number",
title={'text': "<b>Asset Turnover Ratio</b><br><span style='font-size:0.8em;color:gray'>Last Fiscal Year</span>"},
gauge={
'axis': {'range': [min(asset_ratios), max(asset_ratios)], 'tickwidth': 1, 'tickcolor': "darkblue"},
'bar': {'color': "darkblue"},
'bgcolor': "white",
'steps': [
{'range': [min(asset_ratios), max(asset_ratios)], 'color': 'white'},
{'range': [min(asset_ratios), asset_ratios[-1]], 'color': 'lightblue'},
{'range': [asset_ratios[-1], max(asset_ratios)], 'color': 'royalblue'}],
'threshold': {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': asset_ratios[-1]}
}))
fig.update_layout(
title='Asset Turnover (Comparing Companies)',
xaxis_title='Symbols',
yaxis_title='Asset Turnover Ratio',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
import plotly.graph_objects as go
symbols = ['NVDA', 'AVGO', 'TXN', 'QCOM', 'AMD']
def get_current_ratio(symbols, api_key, annual_data):
current_assets = float(annual_data['totalCurrentAssets']) if annual_data['totalCurrentAssets'] != 'None' else 0
current_liabilities = float(annual_data['totalCurrentLiabilities'])
if current_assets == 0:
calculated_current_ratio = None
else:
calculated_current_ratio = current_assets / current_liabilities
return calculated_current_ratio
def create_get_current_ratio(symbols, api_key):
current_ratio = []
for symbol in symbols:
url = f'https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol={symbol}&apikey={api_key}'
response = requests.get(url)
balance_sheet_data = json.loads(response.text)
if 'annualReports' not in balance_sheet_data:
current_ratio.append(None)
continue
annual_data = balance_sheet_data['annualReports'][0]
calculated_current_ratio = get_current_ratio(symbol, api_key, annual_data)
current_ratio.append(calculated_current_ratio)
min_ratio = min(current_ratio)
max_ratio = max(current_ratio)
nvda_ratio = current_ratio[symbols.index('NVDA')]
fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'bar'}, {'type': 'indicator'}]])
fig.add_trace(
go.Bar(x=symbols, y=[0.2, 0.4, 0.5, 0.7, 0.9], name='Current ratio'),
row=1, col=1
)
fig.add_trace(
go.Indicator(
mode='gauge+number',
value=nvda_ratio,
title={'text': "Current Ratio (NVDA)"},
gauge={
'axis': {'range': [min_ratio, max_ratio]},
'steps': [
{'range': [min_ratio, nvda_ratio], 'color': 'red'},
{'range': [nvda_ratio, max_ratio], 'color': 'green'}
],
'threshold': {
'line': {'color': "white", 'width': 4},
'thickness': 0.75,
'value': nvda_ratio
}
}
),
row=1, col=2
)
fig.update_layout(
title='Current Ratio (Comparing Companies)',
xaxis_title='Symbols',
yaxis_title='Operating Margin',
hovermode='x',
template='plotly_dark',
plot_bgcolor='black',
paper_bgcolor='black'
)
return fig
server = Flask(__name__)
external_stylesheets = [dbc.themes.BOOTSTRAP, 'https://maxcdn.bootstrapcdn.com/bootswatch/4.6.0/lux/bootstrap.min.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.H1("NVIDIA Financial Dashboard - A Comprehensive Overview",
style={"fontSize": "80px", "color":"black", "textAlign" : "center"}),
html.Img(src="https://d1lss44hh2trtw.cloudfront.net/resize?type=webp&url=https%3A%2F%2Fshacknews-www.s3.amazonaws.com%2Fassets%2Farticle%2F2021%2F08%2F16%2Flisten-to-the-nvidia-nvda-q2-2022-earnings-conference-call-here_feature.jpg&width=2064&sign=VY1sdHiNdSFZXWzUAWrXBshYvSxLWtOc2I5nR1B4nsc",
style={"width": "30%", "height": "auto", "display": "block", "margin": "auto"}),
html.P("Welcome to the NVIDIA Financial Dashboard, a comprehensive and interactive platform designed to provide valuable insights into NVIDIA Corporation's (NVDA) financial performance, risk profile, and market trends. As a global leader in visual computing and artificial intelligence technologies, NVIDIA plays a significant role in driving innovation and growth in the technology sector.",
style={"fontSize": "28px", "color": "black", "textAlign": "center", "paddingTop": "20px", "paddingBottom": "20px", "paddingLeft" : "10%", "paddingRight" : "10%"}),
html.Div([], style={'borderTop': '2px solid black', 'width': '100%', 'marginBottom': '10px'}),
html.H2("Stock Evaluation", style={"fontSize": "70px", "color": "black", "textAlign": "center"}),
html.Br(),
html.Div([
html.H1("NVIDIA Q4 FY23 Income Statement",
style={"fontSize": "60px", "color":"black", "textAlign" : "center"}),
html.Div([], style={'borderTop': '2px solid black', 'width': '100%', 'marginBottom': '10px'}),
html.Img(
src="https://substackcdn.com/image/fetch/w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F882c21d6-ab03-4a6a-b5cb-9e2c23396b64_2457x1377.png",
style={
"width": "80%",
"height": "auto",
"display": "block",
"margin": "auto",
"marginBottom" : "30px"
}),
html.Div([
dcc.Dropdown(
id="symbol-dropdown",
options=[{'label': ticker, 'value': ticker} for ticker in tickers],
value=tickers[0],
style={"color": 'grey', "fontSize": "40px", "height" : "50", "width": "30%", "display": "block", "margin": "auto"}
),
]),
html.Div([
html.H1("Stock Price chart"),
dcc.Graph(id="stock-chart")
], style={'display': 'inline-block', 'width': '100%','height':'100%','marginLeft': '10px','marginRight': '10px'}),
html.Div([
html.H1("Daily Return"),
dcc.Graph(id="daily-return-chart")
], style={'display': 'inline-block', 'width': '100%','marginLeft': '10px','marginRight': '10px'}),
html.Div([
html.H1("Volume"),
dcc.Graph(id="volume-chart")
], style={'display': 'inline-block', 'width': '100%','marginLeft': '10px','marginRight': '10px'}),
html.Div([
dbc.Button("Productivity", id="productivity-button", className="mr-2", style={'fontSize': '20px'}),
dbc.Button("Profitability", id="profitability-button", className="mr-2", style={'fontSize': '20px'}),
dbc.Button("Liquidity", id="liquidity-button", className="mr-2", style={'fontSize': '20px'}),
dbc.Button("Value", id="value-button", className="mr-2", style={'fontSize': '20px'}),
], className="mb-4", style={'display': 'flex', 'justifyContent': 'space-around', 'width': '60%', 'margin': 'auto'}),
]),
# Section 1
html.Div([
html.Div([
dcc.Graph(id='revenue-chart',style={'display': 'none'})
], style={'display': 'inline-block', 'width': '50%', 'justifyContent': 'center'}),
html.Div([
dcc.Graph(id='costof-revenue-chart',style={'display': 'none'})
], style={'display': 'inline-block', 'width': '50%','justifyContent': 'center'}),
html.Div([
dcc.Graph(id='Operating-income-chart',style={'display': 'none'})
], style={'display': 'inline-block', 'width': '50%','justifyContent': 'center'}),
html.Div([
dcc.Graph(id='Operating-expenses-chart',style={'display': 'none'})
], style={'display': 'inline-block', 'width': '50%'}),
html.Div([
dcc.Graph(id="return-on-equity-chart", figure=create_get_return_on_equity(symbols, api_key),style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%',
'marginBottom': '50px'}),
html.Div([
dcc.Graph(id="return-on-asset-chart", figure=create_get_return_on_asset(symbols, api_key),style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%',
'marginBottom': '50px'}),
html.Div([
dcc.Graph(id="revenue-change-gauge",style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%',
'marginBottom': '50px'}),
html.Div([
dcc.Graph(id="profit-change-gauge",style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="gross-profit-chart", figure=create_get_gross_profit(symbols, api_key),style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="operating-margin-chart", figure=create_get_operating_margin(symbols, api_key),style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="net-profit-margin-chart", figure=create_get_net_profit_margin(symbols, api_key),style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="EPS-chart", figure=create_get_earnings_per_share(symbols, api_key),style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
html.Div([dcc.Graph(id="market-book-chart",figure=create_get_market_book_value(symbols, api_key),style={'display': 'none'})],
style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'
}),
]),
html.Div([
dcc.Graph(id="beta-comparison-chart",figure=plot_beta_comparison(get_beta_values(symbols,api_key)), style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="std-return-chart",style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="debt-equity-chart",figure= create_debt_equity_ratio_chart(symbols, api_key),style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="current-ratio-chart",figure= create_get_current_ratio(symbols, api_key),style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="shares-outstanding-chart",style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="enterprise-value-chart",style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="book-ratio-chart",style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="asset-turnover-chart",style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
html.Div([
dcc.Graph(id="asset-turnover-chart-candle",style={'display': 'none'})
], style={'display': 'flex',
'justifyContent': 'center',
'textAlign': 'center',
'margin': 'auto',
'width': '75%'}),
],style={'backgroundColor': 'white'})
])
@app.callback(
Output("stock-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_chart(symbol):
data = get_stock_data(symbol, api_key)
data['MA20'] = get_moving_averages(data, 20)
data['MA50'] = get_moving_averages(data, 50)
data['MA300'] = get_moving_averages(data, 300)
return create_candlestick_chart(data, symbol)
@app.callback(
Output("daily-return-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_daily_return_chart(symbol):
data = get_stock_data(symbol, api_key)
data = calculate_daily_return(data)
return plot_daily_return(data, symbol)
@app.callback(
Output("volume-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_plot_volume(symbol):
data = get_stock_data(symbol, api_key)
return plot_volume(data, symbol)
@app.callback(
Output("revenue-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_costof_revenue_chart(symbol):
return create_revenue_chart(symbol, api_key)
@app.callback(
Output("costof-revenue-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_costofrevenue_chart(symbol):
return create_costofrevenue_chart(symbol, api_key)
@app.callback(
Output("Operating-income-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_operatingIncome_chart(symbol):
return create_operatingIncome_chart(symbol, api_key)
@app.callback(
Output("Operating-expenses-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_operatingexpenses_chart(symbol):
return create_operatingExpenses_chart(symbol, api_key)
@app.callback(
Output("debt-equity-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_debt_equity_chart(symbol):
return create_debt_equity_ratio_chart(symbol, api_key)
@app.callback(
Output("current-ratio-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_current_ratio_chart(symbol):
return create_get_current_ratio(symbol, api_key)
@app.callback(
Output("shares-outstanding-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_shares_outstanding_chart(symbol):
return create_shares_outstanding_chart(symbol, api_key)
@app.callback(
Output("enterprise-value-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_enterprise_value_chart(symbol):
return create_enterprise_value_chart(symbol, api_key)
@app.callback(
Output("book-ratio-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_get_book_ratio_chart(symbol):
return create_get_book_ratio_chart(symbol, api_key)
@app.callback(
Output("revenue-change-gauge", "figure"),
Input("symbol-dropdown", "value")
)
def update_revenue_change_gauge(symbol):
return create_revenue_change_gauge(symbol, api_key)
@app.callback(
Output("profit-change-gauge", "figure"),
Input("symbol-dropdown", "value")
)
def update_profit_change_gauge(symbol):
return create_profit_change_gauge(symbol, api_key)
@app.callback(
Output("Operating-profit-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_operating_profit_chart(symbol):
return create_operating_profit_chart(symbol, api_key)
@app.callback(
Output("return-on-equity-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_roe_chart(symbol):
return create_get_return_on_equity(symbols, api_key)
@app.callback(
Output("return-on-asset-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_roa_chart(symbol):
return create_get_return_on_asset(symbols, api_key)
@app.callback(
Output("gross-profit-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_gross_profit_chart(symbol):
return create_get_gross_profit(symbol, api_key)
@app.callback(
Output("operating-margin-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_operating_margin_chart(symbol):
return create_get_operating_margin(symbol, api_key)
@app.callback(
Output("net-profit-margin-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_net_profit_margin_chart(symbol):
return create_get_net_profit_margin(symbol, api_key)
@app.callback(
Output("EPS-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_EPS_chart(symbol):
return create_get_earnings_per_share(symbol, api_key)
@app.callback(
Output("market-book-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_market_book_chart(symbol):
return create_get_market_book_value(symbol, api_key)
@app.callback(
Output("beta-comparison-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_beta_comparison_chart(symbol):
beta_values = get_beta_values(tickers, api_key)
return plot_beta_comparison(beta_values)
@app.callback(
Output("std-return-chart", "figure"),
Input("symbol-dropdown", "value")
)
def update_std_return_chart(symbols):
std_returns = get_std_return_data(tickers, api_key)
return plot_std_return_data(std_returns)
@app.callback(
Output("asset-turnover-chart-candle", "figure"),
Input("symbol-dropdown", "value")
)
def update_asset_turnover_chart_candle(symbol):
return create_get_asset_turnover_candle(symbols, api_key)
@app.callback(
[Output("return-on-asset-chart","style"),
Output("return-on-equity-chart","style"),
Output("asset-turnover-chart-candle","style"),
Output("EPS-chart","style"),
Output("gross-profit-chart","style"),
Output("operating-margin-chart","style"),
Output("net-profit-margin-chart","style"),
Output("debt-equity-chart","style"),
Output("beta-comparison-chart","style"),
Output("current-ratio-chart","style"),
Output("market-book-chart","style")],
[Input("productivity-button", "n_clicks"),
Input("profitability-button", "n_clicks"),
Input("liquidity-button", "n_clicks"),
Input("value-button", "n_clicks")]
)
def toggle_charts(prod_btn, prof_btn, liq_btn, val_btn):
changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
if 'productivity-button' in changed_id:
return {'display': 'inline-block','width': '100%','marginLeft': '5px','marginRight': '5px'}, {'display': 'inline-block', 'width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'inline-block','width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'}
elif 'profitability-button' in changed_id:
return {'display': 'none'}, {'display': 'none'},{'display': 'none'},{'display': 'inline-block','width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'inline-block','width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'inline-block','width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'inline-block','width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'}
elif 'liquidity-button' in changed_id:
return {'display': 'none'}, {'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display':'none'},{'display': 'inline-block', 'width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'inline-block', 'width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'inline-block', 'width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'inline-block','width': '100%','marginLeft': '5px','marginRight': '5px'},{'display': 'none'}
elif 'value-button' in changed_id:
return {'display': 'none'}, {'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display':'none'},{'display': 'none'},{'display': 'inline-block', 'width': '100%','marginLeft': '5px','marginRight': '5px'}
return {'display': 'none'}, {'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'},{'display': 'none'}
if __name__ == '__main__':
app.server.run(debug=False, threaded=True, use_reloader=False)
response = requests.get("http://localhost:5000")
# Save the HTML content to a file
with open("C:/Users/tasle/project/dashboard.html", "w", encoding="utf-8") as file:
file.write(response.text)
app.server.shutdown()
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [26/Apr/2023 09:26:21] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "GET /_dash-layout HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "GET /_dash-dependencies HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "GET /_dash-component-suites/dash/dcc/async-dropdown.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "GET /_dash-component-suites/dash/dcc/async-graph.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "GET /_dash-component-suites/dash/dcc/async-plotlyjs.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:24] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:26] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:26] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:26] "GET /_favicon.ico?v=2.9.2 HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:26] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:27] "POST /_dash-update-component HTTP/1.1" 200 -
[2023-04-26 09:26:26,900] ERROR in app: Exception on /_dash-update-component [POST]
Traceback (most recent call last):
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\dash.py", line 1283, in dispatch
ctx.run(
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\_callback.py", line 450, in add_context
output_value = func(*func_args, **func_kwargs) # %% callback invoked %%
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1568000155.py", line 352, in update_gross_profit_chart
return create_get_gross_profit(symbol, api_key)
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\2987020588.py", line 27, in create_get_gross_profit
annual_data = income_statement_data['annualReports'][0] # Get the most recent annual data
KeyError: 'annualReports'
127.0.0.1 - - [26/Apr/2023 09:26:27] "POST /_dash-update-component HTTP/1.1" 500 -
[2023-04-26 09:26:27,296] ERROR in app: Exception on /_dash-update-component [POST]
Traceback (most recent call last):
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\dash.py", line 1283, in dispatch
ctx.run(
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\_callback.py", line 450, in add_context
output_value = func(*func_args, **func_kwargs) # %% callback invoked %%
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1568000155.py", line 373, in update_EPS_chart
return create_get_earnings_per_share(symbol, api_key)
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1251409534.py", line 31, in create_get_earnings_per_share
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
KeyError: 'annualReports'
127.0.0.1 - - [26/Apr/2023 09:26:27] "POST /_dash-update-component HTTP/1.1
" 500 -
127.0.0.1 - - [26/Apr/2023 09:26:27] "POST /_dash-update-component HTTP/1.1" 200 -
[2023-04-26 09:26:27,838] ERROR in app: Exception on /_dash-update-component [POST]
Traceback (most recent call last):
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\dash.py", line 1283, in dispatch
ctx.run(
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\_callback.py", line 450, in add_context
output_value = func(*func_args, **func_kwargs) # %% callback invoked %%
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1568000155.py", line 380, in update_market_book_chart
return create_get_market_book_value(symbol, api_key)
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\2278460934.py", line 26, in create_get_market_book_value
calculated_market_book_value = get_market_book_value(data)
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\2278460934.py", line 7, in get_market_book_value
market_value = float(data['MarketCapitalization']) if data['MarketCapitalization'] != 'None' else 0
KeyError: 'MarketCapitalization'
127.0.0.1 - - [26/Apr/2023 09:26:27] "POST /_dash-update-component HTTP/1.1" 500 -
[2023-04-26 09:26:28,079] ERROR in app: Exception on /_dash-update-component [POST]
Traceback (most recent call last):
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\dash.py", line 1283, in dispatch
ctx.run(
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\_callback.py", line 450, in add_context
output_value = func(*func_args, **func_kwargs) # %% callback invoked %%
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1568000155.py", line 359, in update_operating_margin_chart
return create_get_operating_margin(symbol, api_key)
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\2607406442.py", line 41, in create_get_operating_margin
fig.add_trace(go.Bar(x=symbols, y=operating_margin, name='Bar Chart'), row=1, col=1)
File "C:\Users\tasle\anaconda3\lib\site-packages\plotly\graph_objs\_bar.py", line 3174, in __init__
self["x"] = _v
File "C:\Users\tasle\anaconda3\lib\site-packages\plotly\basedatatypes.py", line 4859, in __setitem__
self._set_prop(prop, value)
File "C:\Users\tasle\anaconda3\lib\site-packages\plotly\basedatatypes.py", line 5203, in _set_prop
raise err
File "C:\Users\tasle\anaconda3\lib\site-packages\plotly\basedatatypes.py", line 5198, in _set_prop
val = validator.validate_coerce(val)
File "C:\Users\tasle\anaconda3\lib\site-packages\_plotly_utils\basevalidators.py", line 404, in validate_coerce
self.raise_invalid_val(v)
File "C:\Users\tasle\anaconda3\lib\site-packages\_plotly_utils\basevalidators.py", line 288, in raise_invalid_val
raise ValueError(
ValueError:
Invalid value of type 'builtins.str' received for the 'x' property of bar
Received value: 'NVDA'
The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
127.0.0.1 - - [26/Apr/2023 09:26:28] "POST /_dash-update-component HTTP/1.1" 500 -
127.0.0.1 - - [26/Apr/2023 09:26:28] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:28] "POST /_dash-update-component HTTP/1.1" 200 -
[2023-04-26 09:26:28,338] ERROR in app: Exception on /_dash-update-component [POST]
Traceback (most recent call last):
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\dash.py", line 1283, in dispatch
ctx.run(
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\_callback.py", line 450, in add_context
output_value = func(*func_args, **func_kwargs) # %% callback invoked %%
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1568000155.py", line 366, in update_net_profit_margin_chart
return create_get_net_profit_margin(symbol, api_key)
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\2997736837.py", line 41, in create_get_net_profit_margin
subplot_fig.add_trace(go.Bar(x=symbols, y=net_profit_margin, name='Bar Chart'), row=1, col=1)
File "C:\Users\tasle\anaconda3\lib\site-packages\plotly\graph_objs\_bar.py", line 3174, in __init__
self["x"] = _v
File "C:\Users\tasle\anaconda3\lib\site-packages\plotly\basedatatypes.py", line 4859, in __setitem__
self._set_prop(prop, value)
File "C:\Users\tasle\anaconda3\lib\site-packages\plotly\basedatatypes.py", line 5203, in _set_prop
raise err
File "C:\Users\tasle\anaconda3\lib\site-packages\plotly\basedatatypes.py", line 5198, in _set_prop
val = validator.validate_coerce(val)
File "C:\Users\tasle\anaconda3\lib\site-packages\_plotly_utils\basevalidators.py", line 404, in validate_coerce
self.raise_invalid_val(v)
File "C:\Users\tasle\anaconda3\lib\site-packages\_plotly_utils\basevalidators.py", line 288, in raise_invalid_val
raise ValueError(
ValueError:
Invalid value of type 'builtins.str' received for the 'x' property of bar
Received value: 'NVDA'
The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
127.0.0.1 - - [26/Apr/2023 09:26:28] "POST /_dash-update-component HTTP/1.1" 500 -
[2023-04-26 09:26:28,406] ERROR in app: Exception on /_dash-update-component [POST]
Traceback (most recent call last):
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\dash.py", line 1283, in dispatch
ctx.run(
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\_callback.py", line 450, in add_context
output_value = func(*func_args, **func_kwargs) # %% callback invoked %%
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1568000155.py", line 282, in update_debt_equity_chart
return create_debt_equity_ratio_chart(symbol, api_key)
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1253813.py", line 23, in create_debt_equity_ratio_chart
annual_data = balance_sheet_data['annualReports'][0] # Get the most recent annual data
KeyError: 'annualReports'
127.0.0.1 - - [26/Apr/2023 09:26:28] "POST /_dash-update-component HTTP/1.1" 500 -
127.0.0.1 - - [26/Apr/2023 09:26:28] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:28] "POST /_dash-update-component HTTP/1.1" 200 -
[2023-04-26 09:26:29,618] ERROR in app: Exception on /_dash-update-component [POST]
Traceback (most recent call last):
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\tasle\anaconda3\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\dash.py", line 1283, in dispatch
ctx.run(
File "C:\Users\tasle\anaconda3\lib\site-packages\dash\_callback.py", line 450, in add_context
output_value = func(*func_args, **func_kwargs) # %% callback invoked %%
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\1568000155.py", line 289, in update_current_ratio_chart
return create_get_current_ratio(symbol, api_key)
File "C:\Users\tasle\AppData\Local\Temp\ipykernel_16272\292640255.py", line 32, in create_get_current_ratio
min_ratio = min(current_ratio)
TypeError: '<' not supported between instances of 'float' and 'NoneType'
127.0.0.1 - - [26/Apr/2023 09:26:29] "POST /_dash-update-component HTTP/1.1" 500 -
127.0.0.1 - - [26/Apr/2023 09:26:30] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:30] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:31] "POST /_dash-update-component HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2023 09:26:31] "POST /_dash-update-component HTTP/1.1" 200 -